package xtcp

import (
	"net"
	"gitee.com/cooge/impush/core"
	"errors"
	"gitee.com/cooge/impush/xtcp/conn"
)

type XTcpServer  struct{
	listener *net.TCPListener
}

func NewXTcpServer()*XTcpServer{
	var tt XTcpServer
	return &tt
}

func (this *XTcpServer) Bind(lport int) error {
	conn, err := net.ListenTCP("tcp4", &net.TCPAddr{
		IP:   net.IPv4(0, 0, 0, 0),
		Port: lport,
	})
	if err == nil {
		core.AddInfo("XTCP_PORT", lport)
		this.listener = conn
	}
	return err
}
func (this *XTcpServer) Accept() (*conn.XTcpConn, error) {
	if this.listener != nil {
		tcn, err := this.listener.Accept()
		if err == nil {
			nt, ok := tcn.(*net.TCPConn)
			if ok {
				return conn.NewXTcpConn(nt),nil
			} else {
				return nil, errors.New("XTCP ERROR")
			}
		} else {
			return nil, err
		}
	}
	return nil, errors.New("SYS XTCP ERROR")
}